
function catch_keydown(sel) { switch(event.keyCode) {

    case 13: //Enter;

        sel.options[sel.length] = new Option("","",false,true);

        event.returnValue = false;

        break;

    case 27: //Esc;

        alert("text:" + sel.options[sel.selectedIndex].text + ", value:" + sel.options[sel.selectedIndex].value + ";");

        event.returnValue = false;

        break;

    case 46: //Delete;

        if(confirm("刪除當前內容!?")) {

            sel.options[sel.selectedIndex] = null;

            if(sel.length>0) { sel.options[0].selected = true; } }

        event.returnValue = false; break;

    case 8: //Back Space;

        var s = sel.options[sel.selectedIndex].text;

        sel.options[sel.selectedIndex].text = s.substr(0,s.length-1);

        event.returnValue = false; break; } }

function catch_press(sel) {

    sel.options[sel.selectedIndex].text = sel.options[sel.selectedIndex].text + String.fromCharCode

    (event.keyCode); event.returnValue = false;

}



function getYMDHMS (timestamp) {
    let time = new Date(timestamp)
    let year = time.getFullYear()
    const month = (time.getMonth() + 1).toString().padStart(2, '0')
    const date = (time.getDate()).toString().padStart(2, '0')
    const hours = (time.getHours()).toString().padStart(2, '0')
    const minute = (time.getMinutes()).toString().padStart(2, '0')
    const second = (time.getSeconds()).toString().padStart(2, '0')

    return year + '-' + month + '-' + date+' '+hours+':'+minute+':'+second;
}



layui.use('table', function () {
    var table = layui.table;
    //第一个实例
    table.render({
        elem: '#demo'
        , url:'/curriculumFind' //数据接口
        , method: 'post'
        , page: true //开启分页
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , limit: 7
        , id:'testReload'
        , limits: [3, 5, 7]
        , cols: [[
            { width: 80, type: 'checkbox' },
            { field: 'pkId', width: 100, title: '主键ID',hide:true },
            { field: 'curriculumCode', width: 100,title: '课程代码',sort: true},
            { field: 'curriculumName', width: 100,title: '课程名称',event:'setSign', style:'cursor: pointer;'},
            { field: 'curriculumTeacherId', width: 135,title: '授课老师ID',sort: true},
            { field: 'curriculumTeacherName', width: 120, title: '授课老师名称'},
            { field: 'curriculumDuration', width: 90,title: '时长/分钟'},
            { field: 'curriculumType', width: 100,title: '课程类型'},
            { field: 'curriculumDescription', width: 100,title: '课程描述'},
            { field: 'deleteFlag', width: 90,title: '删除标识',hide:true},
            { field: 'creator', width: 110,title: '创建者'},
            { field: 'createTime', width: 160,title: '创建时间'},
            { field: 'updateTime', width: 160,title: '修改时间'},
            { field: 'right', width:140, title: '操作', toolbar: '#barDemo' },
        ]],


        done: function(res, curr, count) {
            // $("[data-field='area']").children().each(function () {
            //     if ($(this).text() == '1') {
            //         $(this).text('A区');
            //     } else if ($(this).text() == '2') {
            //         $(this).text('B区');
            //     } else if ($(this).text() == '3') {
            //         $(this).text('C区');
            //     } else if ($(this).text() == '4') {
            //         $(this).text('D区');
            //     }
            // });
            $("[data-field='curriculumType']").children().each(function () {
                if ($(this).text() == '0') {
                    $(this).text('未分配');
                } else if ($(this).text() == '1') {
                    $(this).text('小学课程');
                }
                else if ($(this).text() == '2') {
                    $(this).text('中学课程');
                }
                else if ($(this).text() == '3') {
                    $(this).text('大学课程');
                }
                else if ($(this).text() == '4') {
                    $(this).text('培训机构');
                }
                else if ($(this).text() == '5') {
                    $(this).text('特长课');
                }
            });



            $("[data-field='createTime']").children().each(function () {

                var birthday = $(this).text();
                if(birthday.indexOf('创建时间')==-1){
                    $(this).text(getYMDHMS(birthday));
                }

            });

            $("[data-field='updateTime']").children().each(function () {

                var birthday = $(this).text();

                if(birthday.indexOf('修改时间')==-1){
                    $(this).text(getYMDHMS(birthday));
                }

            });

        },
        parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": res.data //解析数据列表
            };
        },
        request: {
            pageName: 'page' // 页码的参数名称，默认：page
            , limitName: 'limit' //每页数据量的参数名，默认：limit
        },




    });


    //监听行单击事件（双击事件为：rowDouble）
    // table.on('row(test)', function(obj){
    //     var data = obj.data;
    //
    //     layer.alert(JSON.stringify(data), {
    //         title: '当前行数据：'
    //     });
    //     //标注选中样式
    //     obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    // });


    table.on('sort(test)',function(obj){
        table.reload('testReload', {
            initSort:obj

        });

    });
    table.reload('testReload',{})
    //表单数据重载
    var $ = layui.$,active = {
        reload: function(){
            var curriculumName=$("#curriculumNameId");
            var curriculumTeacherName=$("#curriculumTeacherNameId");
            var curriculumType=$("#curriculumTypeId");
            //执行重载
            table.reload('testReload', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where: {

                    curriculumName: curriculumName.val(),
                    curriculumTeacherName: curriculumTeacherName.val(),
                    curriculumType: curriculumType.val(),

                }

            });
        }
    };

    $('.demoTable .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    //监听头工具事件
    table.on('toolbar(test)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id)
            ,data = checkStatus.data //获取选中的数据
            ,delList=[]
            ,delListCurrName=" "

        for(var i=0;i<data.length;i++){
            delList.push(data[i].pkId);
            delListCurrName+=data[i].curriculumName+" "
        }
        var json={"pkId":delList};

        switch(obj.event){
            case 'add':
                layer.msg('添加');
                layer.open({
                    type: 1 //此处以iframe举例
                    , title:'宿舍信息录入表'
                    , area: ['800px', '650px']
                    , shade: 0
                    , maxmin: true
                    ,content:$("#insertpage")
                })

                $("#addCurr").click(function () {
                    var istData={
                        "curriculumCode":$("#curriculumCodeIddd").val(),
                        "curriculumName":$("#curriculumNameIddd").val(),
                        "curriculumTeacherName":$("#curriculumTeacherNameIddd").val(),
                        "curriculumDuration":$("#curriculumDurationIddd").val(),
                        "curriculumDescription":$("#curriculumDescriptionIddd").val(),
                        "curriculumType":$("#curriculumTypeIddd").val(),
                        "creator":$("#creatorId").val(),
                    }

                    $.ajax({
                        type:"post",
                        url:"/insertCurriculum",
                        data:JSON.stringify(istData),
                        contentType: "application/json;charset=utf-8",
                        dataType:"json",
                        success:function (istData) {
                            if(istData.code=='0000'){
                                layer.msg(''+istData.msg,{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(istData.code=='9999'){
                                layer.msg(''+istData.msg,{icon:5,time:1000},function () {
                                })
                            }
                        },error:function (error) {
                            layer.msg("添加请求失败")
                        }

                    });
                })

                break;
            case 'update':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else if(data.length > 1){
                    layer.msg('只能同时编辑一个');
                } else {
                    layer.alert('编辑 [id]：'+ checkStatus.data[0].id);
                }
                break;
            case 'delete':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else {
                    layer.confirm('确认'+delListCurrName+'科目删除吗?', function(index){
                        $.ajax({                //批量删除
                            type:"post",
                            url:"/deleteListCurr",
                            contentType: "application/json;charset=utf-8",
                            data:JSON.stringify(json),
                            dataType:"json",
                            success:function (delData) {
                                if(delData >=1){
                                    layer.msg('删除成功',{icon:6,time:1000},function () {
                                        window.location.reload();
                                    })
                                }else if(delData < 1) {
                                    layer.msg('删除失败', {icon: 5, time: 1000}, function () {
                                        window.location.reload();
                                    })
                                }
                            },error:function (error) {
                                layer.msg("删除请求失败");
                            }
                        })
                    });
                    break;
                }
        };
    });



    //监听行工具事件
    table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event //获得 lay-event 对应的值
            ,dropdown=layui.dropdown;
        if(layEvent ==='setSign'){
            layer.open({
                type: 1 //此处以iframe举例
                , title:'课程'+data.curriculumName+'的信息'
                , area: ['800px', '600px']
                , shade: 0
                , maxmin: true
                ,content:$("#viewcurr")
            })
            $("#curriculumCodeIdddd").val(data.curriculumCode);
            $("#curriculumNameIdddd").val(data.curriculumName);
            $("#curriculumTeacherNameIdddd").val(data.curriculumTeacherName);
            $("#curriculumDurationIdddd").val(data.curriculumDuration);
            $("#curriculumDescriptionIdddd").val(data.curriculumDescription);
            $("#curriculumTypeIdddd").val(data.curriculumType);
        }

        if(layEvent === 'detail') {

            layer.open({
                type: 1 //此处以iframe举例
                , title:'课程'+data.curriculumName+'的信息'
                , area: ['800px', '600px']
                , shade: 0
                , maxmin: true
                ,content:$("#viewcurr")
            })
            $("#curriculumCodeIdddd").val(data.curriculumCode);
            $("#curriculumNameIdddd").val(data.curriculumName);
            $("#curriculumTeacherNameIdddd").val(data.curriculumTeacherName);
            $("#curriculumDurationIdddd").val(data.curriculumDuration);
            $("#curriculumDescriptionIdddd").val(data.curriculumDescription);
            $("#curriculumTypeIdddd").val(data.curriculumType);


            // layer.open({
            //     type: 1 //此处以iframe举例
            //     , title:'宿舍'+data.dormitoryName+'的信息'
            //     , area: ['800px', '600px']
            //     , shade: 0
            //     , maxmin: true
            //     ,content:$("#viewdor")
            //     ,end:function () {
            //         window.location.reload();
            //     }
            // })
            // $("#areaIddd").val(data.area);
            // $("#buildingFloorIddd").val(data.buildingFloor);
            // $("#buildingNoIddd").val(data.buildingNo);
            // $("#dormitoryNameIddd").val(data.dormitoryName);
            // $("#bedNumberIddd").val(data.bedNumber);
            // $("#dormSupervisorIddddd").val(data.dormSupervisor);
            // $("#useStatusIddd").val(data.useStatus);

            //添加学生按钮
            // $("#adddorr").click(function () {
            //     let  Id=data.pkId;
            //     layer.open({
            //         type: 2 //此处以iframe举例
            //         , area: ['1300px', '700px']
            //         , shade: 0
            //         , maxmin: true
            //         ,content:"/selectKeydor/"+Id
            //
            //     })
            //
            // })
             //查看学生信息按钮
            // $("#viewDorm").click(function () {
            //     let  Id=data.dormitoryId;
            //     layer.open({
            //         type: 2 //此处以iframe举例
            //         , area: ['1300px', '700px']
            //         , shade: 0
            //         , maxmin: true
            //         ,content:"/viewstu/"+Id
            //
            //     })
            //
            //
            // })



        } else if(layEvent === 'more'){
            //下拉菜单
            dropdown.render({
                elem: this //触发事件的 DOM 对象
                ,show: true //外部事件触发即显示
                ,data: [{
                    title: '编辑'
                    ,id: 'edit'
                },{
                    title: '删除'
                    ,id: 'del'
                }]
                ,click: function(menudata){
                    if(menudata.id === 'del'){
                        layer.confirm('真的删除'+data.curriculumName+'科目么', function(index){
                            //删除对应行（tr）的DOM结构
                            //layer.close(index);
                            //向服务端发送删除指令

                            $.ajax({
                                type:'post',
                                url:"/curriculumDelete",
                                data:JSON.stringify(data),
                                contentType:'application/json;charset=utf-8',
                                dataType:"json",
                                success:function (data) {
                                    if(data=='1'){
                                        layer.msg('删除成功',{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(data=='0'){
                                        layer.msg('删除失败',{icon:5,time:1000},function () {
                                        })
                                    }
                                },error:function (error) {
                                    alert("请求失败")
                                }

                            })
                        });
                    } else if(menudata.id === 'edit'){

                        layer.msg('编辑操作，当前行 ID:'+ data.pkId);
                        layer.open({
                            type: 1 //此处以iframe举例
                            , title:'课程信息'
                            , area: ['800px', '600px']
                            , shade: 0
                            , maxmin: true
                            ,content:$("#updatePage")
                        })
                        //数据回显
                        $("#curriculumCodeIdd").val(data.curriculumCode);
                        $("#curriculumNameIdd").val(data.curriculumName);
                        $("#curriculumTeacherNameIdd").val(data.curriculumTeacherName);
                        $("#curriculumDurationIdd").val(data.curriculumDuration);
                        $("#curriculumDescriptionIdd").val(data.curriculumDescription);
                        $("#curriculumTypeIdd").val(data.curriculumType);

                        $("#updatecurriculum").click(function () {
                            var updData={
                                "pkId":data.pkId,
                                "curriculumCode":$("#curriculumCodeIdd").val(),
                                "curriculumName":$("#curriculumNameIdd").val(),
                                "curriculumTeacherName":$("#curriculumTeacherNameIdd").val(),
                                "curriculumDuration":$("#curriculumDurationIdd").val(),
                                "curriculumDescription":$("#curriculumDescriptionIdd").val(),
                                "curriculumType":$("#curriculumTypeIdd").val(),

                            }
                            $.ajax({
                                type:"post",
                                url:"/updatecurr",
                                data:JSON.stringify(updData),
                                contentType: "application/json;charset=utf-8",
                                dataType:"json",
                                success:function (upddata) {
                                    if(upddata.code=='0000'){
                                        layer.msg(''+upddata.msg,{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(upddata.code=='9999'){
                                        layer.msg(''+upddata.msg,{icon:5,time:1000},function () {
                                        })
                                    }
                                },error:function (error) {
                                    layer.msg("修改请求失败")
                                }


                            })
                        })

                    }
                }

                ,align: 'right' //右对齐弹出（v2.6.8 新增）
                ,style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
            })
        }
    });
});

//JS
layui.use(['element', 'layer', 'util'], function(){
    var element = layui.element
        ,layer = layui.layer
        ,util = layui.util
        ,$ = layui.$;

    //头部事件
    util.event('lay-header-event', {
        //左侧菜单事件
        menuLeft: function(othis){
            layer.msg('展开左侧菜单的操作', {icon: 0});
        }
        ,menuRight: function(){
            layer.open({
                type: 1
                ,content: '<div style="padding: 15px;">处理右侧面板的操作</div>'
                ,area: ['260px', '100%']
                ,offset: 'rt' //右上角
                ,anim: 5
                ,shadeClose: true
            });
        }
    });

});

layui.config({
    version: '1623988781494' //为了更新 js 缓存，可忽略
});
layui.use('form', function(){
    var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功

    //……

    //如果你的 HTML 是动态生成的，自动渲染就会失效
    //因此你需要在相应的地方，执行下述方法来进行渲染
    form.render('select');
});
//输入框获得焦点
$("#curriculumCodeIdd").focus(function(){
    $("#curriculumCodeIdd").css("background-color","#fff");
});

//失去焦点
$("#curriculumCodeIdd").blur(function(){
    $("#curriculumCodeIdd").css("background-color","#fff");


    var updData={
        "curriculumCode":$("#curriculumCodeIdd").val(),
    }
    $.ajax({
        type:"post",
        url:"/codeXiaoyan",
        data:updData,
        dataType:"json",
        success:function (upddata) {
            if (upddata==1){
                layer.msg("课程代码已存在")
            }
        },error:function (error) {
            layer.msg("请求失败")
        }


    })

});

$("#curriculumCodeIddd").blur(function(){
    $("#curriculumCodeIddd").css("background-color","#fff");


    var updData={
        "curriculumCode":$("#curriculumCodeIddd").val(),
    }
    $.ajax({
        type:"post",
        url:"/codeXiaoyan",
        data:updData,
        dataType:"json",
        success:function (upddata) {
            if (upddata==1){
                layer.msg("课程代码已存在")
            }
        },error:function (error) {
            layer.msg("请求失败")
        }


    })

});
